package com.sdjictec.haier.utils;

import org.apache.axis.encoding.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * 加解密
 * */
public class EncryptUtil {

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @param secureKey 加密秘钥
     * @return
     */
    public static String encode(String content, String secureKey) throws Exception{
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(secureKey.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        byte[] byteContent = content.getBytes("utf-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(byteContent);
        return Base64.encode(result); // base64转码
    }


    /**
     * 解密
     *
     * @param content 待解密内容
     * @param secureKey 解密秘钥
     * @return
     */
    public static String decode(String content, String secureKey) throws Exception{
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(secureKey.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
        byte[] base64Dec = Base64.decode(content);
        byte[] result = cipher.doFinal(base64Dec);
        return new String(result);
    }


//    public static void main(String[] args) throws Exception {
//        if(args==null||StringUtils.isEmpty(args[0])||StringUtils.isEmpty(args[2])){
//            System.out.println("请输入完整的参数");
//        }
//        else{
//            String source = args[0];
//            String key = args[1];
//            System.out.println(encode(source,key));
//        }
//    }
}
